<template>
  <div class="wai">
    <div class="left f f-a-c f-j-c">
      <button @click="scanning">扫描附近的设备</button>
    </div>
    <div class="right">
      <div v-for="(item, index) in list" :key="index" class="item">
        <div class="f f-a-c">
          <div class="itemBox">设备名称(name)：{{ item.name }}</div>
          <div class="itemBox">设备名称(localName)：{{ item.localName }}</div>
        </div>
        <div class="f f-a-c">
          <div class="itemBox">deviceId：{{ item.deviceId }}</div>
          <div class="itemBox">
            advertisServiceUUIDs：{{ item.advertisServiceUUIDs }}
          </div>
        </div>
        <div class="f f-a-c">
          <div class="itemBox">信号强度(RSSI):{{ item.RSSI }}</div>
          <div class="itemBox">advertisData:{{ item.advertisData }}</div>
        </div>
        <div>
          <button @click="connectBluetooth(item)">连接蓝牙</button>
          <!-- <button @click="connectBluetoothTZ(item)">获取特征</button> -->
          <button @click="svatMessage(item)">发送消息</button>
        </div>
      </div>
    </div>
    <!-- <div class="" @click="dianClick">点我</div> -->
    <van-popup v-model="show">
      <div
        style="
          width: 500px;
          height: 300px;
          overflow: auto;
          background-color: aquamarine;
        "
      >
        <div style="text-align: center">蓝牙信息</div>
        <div>{{ info }}</div>
      </div>
    </van-popup>
    <van-popup v-model="shows">
      <div
        class="f f-a-c f-j-c"
        style="
          width: 500px;
          height: 300px;
          overflow: auto;
          background-color: aquamarine;
        "
      >
        <input
          v-model="tezheng.value"
          style="width: 80%; height: 30px; margin-bottom: 10px"
          type="text"
          name=""
          placeholder="请输入消息"
          id=""
        />
        <button @click="sendDataToDevice">发送消息</button>
      </div>
    </van-popup>
  </div>
</template>

<script>
// import TcpSocket from "react-native-tcp-socket";
import { Toast } from "vant";
export default {
  data() {
    return {
      info: {},
      tezheng: { deviceId: "", advertisServiceUUIDs: "", uuid: "", value: "" },
      shows: false,
      show: false,
      list: [],
    };
  },

  methods: {
    svatMessage() {
      this.shows = true;
    },
    listFn(list) {
      Toast("提示");
      console.log(JSON.stringify(list), "1411111111111111111111111111");
      let arr = [];
      list.forEach((element) => {
        if (element.properties.write == true) {
          console.log(element, "2222222222222222222222222222222");
          arr.push(element);
        }
      });
      return arr;
    },
    sendDataToDevice() {
      let buffer = new Uint8Array([this.tezheng.value]).buffer; // 发送的数据要转成 buffer
      plus.bluetooth.writeBLECharacteristicValue({
        deviceId: this.tezheng.deviceId,
        serviceId: this.tezheng.advertisServiceUUIDs,
        characteristicId: this.tezheng.uuid,
        value: buffer,
        success: (cheng) => {
          Toast("发送成功");
          console.log(JSON.stringify(cheng));
          console.log("数据发送成功");
        },
        fail: (error) => {
          Toast(`发送失败${JSON.stringify(error)}`);
        },
      });
    },

    // 获取特征
    connectBluetoothTZ(item) {
      // 获取设备特征
      plus.bluetooth.getBLEDeviceCharacteristics({
        deviceId: item.deviceId,
        serviceId: item.advertisServiceUUIDs,
        success: (res) => {
          console.log("特征信息", JSON.stringify(res));
          this.info = JSON.stringify(res);
          this.show = true;
          // 先注释掉
          let lists = this.listFn(res.characteristics);
          let n = JSON.stringify(res);
          this.info = n;
          if (lists.length == 0) {
            Toast("该蓝牙设备不允许直接通过特征写入数据");
            return;
          }
          this.tezheng.uuid = lists[0].uuid;
          // Toast("获取特征成功");
          // this.tezheng = {
          //   deviceId: item.deviceId,
          //   advertisServiceUUIDs: item.advertisServiceUUIDs[0],
          //   uuid: lists[0].uuid,
          // };
          // console.log("特征列表：", n);
          // // 找到合适的特征 UUID
        },
        fail: function (error) {
          Toast("获取特征失败");
          let n = JSON.stringify(error);
          console.error("获取特征失败：", n, error);
        },
      });
    },
    // 点击链接
    connectBluetooth(item) {
      plus.bluetooth.createBLEConnection({
        deviceId: item.deviceId,
        success: (re) => {
          Toast("成功连接到设备");
          let n = JSON.stringify(re);
          console.log("成功连接到设备:", n, re);
          setTimeout(() => {
            plus.bluetooth.getConnectedBluetoothDevices({
              success: (rr) => {
                console.log("rrrrrrrrrrrrrrrrrrrrr", JSON.stringify(rr));

                // 获取设备的服务信息
                plus.bluetooth.getBLEDeviceServices({
                  deviceId: item.deviceId,
                  success: (res) => {
                    this.info = res.services;
                    this.show = true;
                    console.log(
                      "设备服务 UUIDs:",
                      JSON.stringify(res.services)
                    );
                    // 选择需要的 serviceId
                    this.tezheng.deviceId = item.deviceId; // 获取第一个设备的 ID
                    this.tezheng.advertisServiceUUIDs = res.services[0].uuid; // 获取第一个服务的 UUID
                    // console.log("选中的服务UUID:", serviceId);
                    // 获取特征
                    this.connectBluetoothTZ(this.tezheng);
                  },
                  fail: (error) => {
                    console.error("获取服务失败:", error);
                  },
                });

                // 先注释掉获取特征

                // let n = JSON.stringify(rr);
                // this.info = n;
                // // this.show = true;
                // console.log("已连接的设备信息:", n);
              },
              fail: function (err) {
                console.error("获取已连接设备失败:", err);
              },
            });
          }, 2000);
        },
        fail: function (errorss) {
          if (errorss.message == "already connect") {
            return Toast("已连接该设备");
          }

          Toast("连接失败");
          let n = JSON.stringify(errorss);
          console.error("连接设备失败：", n, errorss);
        },
      });
    },
    scanning() {
      // 获取蓝牙列表
      plus.bluetooth.openBluetoothAdapter({
        success: (res) => {
          console.log("蓝牙模块初始化成功", res);
          plus.bluetooth.startBluetoothDevicesDiscovery({
            services: [], // 指定要搜索的蓝牙设备主服务UUID列表，为空则搜索所有
            success: (ress) => {
              let n = JSON.stringify(ress);
              console.log("开始搜索设备", ress, n);
              setTimeout(() => {
                plus.bluetooth.getBluetoothDevices({
                  success: (devices) => {
                    let n = JSON.stringify(devices);
                    console.log(
                      "已发现的设备：",
                      JSON.stringify(devices.devices)
                    );
                    this.list = devices.devices;
                  },
                  fail: function (error) {
                    console.error("获取设备列表失败：", error);
                  },
                });
              }, 5000);
            },
            fail: function (error) {
              console.error("搜索设备失败：", error);
            },
          });
        },
        fail: function (error) {
          console.error("蓝牙模块初始化失败：", error);
        },
      });
    },
  },
};
</script>

<style>
* {
  padding: 0;
  margin: 0;
}
.wai {
  width: 100vw;
  height: 100vh;
  background-color: blanchedalmond;
  display: flex;
  align-items: center;
  justify-content: center;
}
.left {
  width: 20%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: pink;
}
.right {
  width: 80%;
  height: 100%;
  background-color: rgb(104, 218, 129);
  overflow: auto;
}
.item {
  width: 100%;
  height: 100px;
  background-color: beige;
  margin-bottom: 10px;
  overflow: auto;
}
.f {
  display: flex;
}
.f-a-c {
  align-items: center;
}
.f-j-c {
  justify-content: center;
}
</style>
